package com.wn.netty.group;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

/**
 * @FileName: NettyClient
 * @Description: TODO
 * @Author: MaWenHao
 * @Created: 2020/8/5 - 14:30
 * @Version: V1.0
 * @Company: 东方微银科技（北京）有限公司
 */
public class NettyClient {

    private static final int CORE_THREAD_COUNT = Runtime.getRuntime().availableProcessors();

    private static final int PORT = 8888;
    private static final String ADDRESS = "127.0.0.1";

    public static void main(String[] args) {
        // 创建时间循环组
        EventLoopGroup group = new NioEventLoopGroup(CORE_THREAD_COUNT);
        try {
            // 创建客户端启动器
            Bootstrap bootstrap = new Bootstrap();
            // 设置参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast("decoder", new StringDecoder())
                                    .addLast("encoder", new StringEncoder())
                                    .addLast(new SimpleClientChannelHandler());
                        }
                    });
            // 启动并连接
            ChannelFuture channelFuture = bootstrap.connect(ADDRESS, PORT).sync();
            Channel channel = channelFuture.channel();
            System.out.println("--------------" + channel.localAddress() + "--------------");
            // 监听控制台输出
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()) {
                String msg = scanner.nextLine();
                channel.writeAndFlush(msg);
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
